<template>
  <div class="app-container" v-loading="exploading"
    element-loading-text="正在导出，请稍候..."
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    >
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
       <el-form-item label="" prop="grantId">
        <el-select v-model="queryParams.grantId" placeholder="请选择项目" @change="grantSelectChange">
          <el-option
            v-for="dict in grantOptions"
            :key="dict.grantId"
            :label="dict.grantName"
            :value="dict.grantId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="sceneId">
        <el-select v-model="queryParams.sceneId" clearable placeholder="请选择场次"  @change="sceneSelectChange">
          <el-option
            v-for="dict in sceneOptions"
            :key="dict.id"
            :label="dict.sceneName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择签到状态" >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="examinerIdText">
        <el-input
          v-model="queryParams.examinerIdText"
          placeholder="请输入姓名"
          clearable
          size="small"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="" prop="idCardText">
        <el-input
          v-model="queryParams.idCardText"
          placeholder="请输入身份证号"
          clearable
          size="small"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="" prop="subjectCodeText">
        <el-input
          v-model="queryParams.subjectCodeText"
          placeholder="请输入课目"
          clearable
          size="small"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['grant:examinerscene:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['grant:examinerscene:remove']"
        >批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          @click="handleImport"
          v-hasPermi="['']"
        >导入考场和考场地址</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="importTemplate"
          v-hasPermi="['grant:examinerscene:export']"
        >下载模板</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          @click="countExaminerPrice"
        >计算发放费用</el-button>
      </el-col>

    </el-row>

    <el-table v-loading="loading" :data="examinersceneList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="考点" align="center" prop="examPointIdText" width="180"/>
      <el-table-column label="人员" align="center" prop="examinerIdText" width="100"/>
      <el-table-column label="科类" align="center" prop="typeText" width="150"/>
      <el-table-column label="科目" align="center" prop="subjectCodeText" width="150"/>
      <el-table-column label="人员电话" align="center" prop="phoneText" width="150"/>
      <el-table-column label="身份证" align="center" prop="idCardText" width="180"/>
      <el-table-column label="派出单位" align="center" prop="companyName" width="120"/>
      <el-table-column label="所在考场" align="center" prop="examRoom" width="120"/>
      <el-table-column label="考场地址" align="center" prop="roomAddr" width="150"/>
      <el-table-column label="签到状态" align="center" prop="status" width="120" :formatter="statusFormat" />
      <el-table-column label="签到时间" align="center" prop="time" width="160"/>
      <el-table-column label="签到人员姓名" align="center" prop="signExaminerName" width="120"/>
      <el-table-column label="替换人员姓名" align="center" prop="replaceExaminerName" width="120"/>
      <el-table-column label="替换人员身份证" align="center" prop="replaceExaminerIdcard" width="180"/>
      <el-table-column label="替换人员电话" align="center" prop="replaceExaminerPhone" width="150"/>
      <el-table-column label="备注" align="center" prop="remark" width="160"/>
      <el-table-column label="签到备注" align="center" prop="signRemark" width="160"/>
      <el-table-column label="阅卷天数" align="center" prop="signDay" width="160"/>
      <el-table-column label="每天费用" align="center" prop="dayPrice" width="160"/>
      <el-table-column label="税费" align="center" prop="taxPrice" width="160"/>
      <el-table-column label="合计应发" align="center" prop="sumPrice" width="160"/>
      <el-table-column label="费用类型" align="center" prop="examinerType" width="160"/>


      <el-table-column label="操作" align="center"  fixed="right"  class-name="small-padding fixed-width" width="80">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['grant:examinerscene:edit']"
          >修改</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改人员签到对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-form-item label="签到状态">
            <el-radio-group v-model="form.sceneStatus">
              <el-radio :label="0">未操作</el-radio>
              <el-radio :label="1">正常</el-radio>
              <el-radio :label="2">迟到</el-radio>
              <el-radio :label="3">未到</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="费用类型">
              <el-select v-model="form.examinerType" placeholder="费用类型">
                <el-option key="考官" label="考官" value = "考官"/>
                <el-option key="组长" label="组长" value = "组长"/>
                <el-option key="优秀" label="优秀" value = "优秀"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="阅卷天数" prop="signDay">
              <el-input-number v-model="form.signDay" :precision="0" :step="1"  placeholder="请输入阅卷天数" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="每天费用" prop="dayPrice">
              <el-input-number v-model="form.dayPrice" :precision="2" :step="0.01"  placeholder="请输入每天费用" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="税费" prop="taxPrice">
              <el-input-number v-model="form.taxPrice" :precision="2" :step="0.01"  placeholder="请输入税费" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="合计应发" prop="sumPrice">
              <el-input-number v-model="form.sumPrice" :precision="2" :step="0.01"  placeholder="请输入合计应发" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?grantId=' + queryParams.grantId+'&sceneId=' + queryParams.sceneId+'&examinerPointId=' + queryParams.exampointId"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listExaminerscene, getExaminerscene, delExaminerscene, addExaminerscene, updateExaminerscene, exportExaminerscene,updateExaminerSceneStatus,downTemplate,countExaminerPrice } from "@/api/grant/examinerscene";
import {listGrantAll} from "@/api/grant/grant";
import { listScene} from "@/api/grant/scene";
import { getToken } from "@/utils/auth";
import ExportJsonExcel from "js-export-excel";
export default {
  name: "Examinerscene",
  data() {
    return {
      exploading:false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 人员签到表格数据
      examinersceneList: [],
      grantOptions: [],
      sceneOptions: [],
      statusOptions: [{'dictValue':"-1",'dictLabel':'全部'},{'dictValue':"0",'dictLabel':'未操作'},{'dictValue':"1",'dictLabel':'正常'}
              ,{'dictValue':"2",'dictLabel':'迟到'},{'dictValue':"3",'dictLabel':'未到'}],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        grantId: undefined,
        exampointId: undefined,
        sceneId: undefined,
        examinerId: undefined,
        time: undefined,
        status: "-1",
        examRoom: undefined,
        roomAddr: undefined,
        signExaminerId: undefined,
        replaceExaminerId: undefined,
        signRemark: undefined,
        examinerIdText: undefined,
        idCardText: undefined,
        subjectCodeText: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/grant/examinerscene/importData"
      }
    };
  },
  created() {
    let query ={};
    query["isEnabled"]="0";
    listGrantAll(query).then(res=>{
      this.grantOptions = res.data;

      this.queryParams.grantId=res.data[res.data.length-1].grantId;

      listScene(this.queryParams).then(response => {

        this.sceneOptions = response.rows;

        this.getList();
      });
    })

  },
  methods: {

    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    grantSelectChange(value)
    {
      this.queryParams.grantId=value;
      listScene(this.queryParams).then(response => {
        this.sceneOptions = response.rows;
        if(this.sceneOptions.length>0)
        {
          this.queryParams.sceneId = this.sceneOptions[0].id;
          this.queryParams.exampointId = this.sceneOptions[0].exampointId;
        }else{
          this.queryParams.sceneId = undefined;
          this.queryParams.exampointId = undefined;
        }
      });

    },
    sceneSelectChange(value)
    {
      this.queryParams.sceneId = value;
      this.sceneOptions.forEach(item => {
         if(item.id==value){
          this.queryParams.exampointId = item.exampointId;
         }
      })
      console.log(this.queryParams.sceneId,this.queryParams.exampointId)
    },
    /** 查询人员签到列表 */
    getList() {
      this.loading = true;
      listExaminerscene(this.queryParams).then(response => {
        this.examinersceneList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        grantId: undefined,
        exampointId: undefined,
        sceneId: undefined,
        examinerId: undefined,
        time: undefined,
        sceneStatus: "-1",
        examRoom: undefined,
        roomAddr: undefined,
        signExaminerId: undefined,
        replaceExaminerId: undefined,
        remark: undefined,
        signRemark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加人员签到";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getExaminerscene(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改签到状态";
      });
    },
    /** 导入 按钮操作 */
    handleImport() {
      this.upload.title = "考场和考试地址导入";
      this.upload.open = true;
    },
        /** 下载模板操作 */
    importTemplate() {
      return downTemplate().then(res=>{
        this.download(res.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      console.log('response',response)
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      //导出失败的记录
      if(response.data!=null)
      {
        this.exportExcel(response.data)
      }
      this.getList();
    },
    exportExcel(list) {

      const dataList = list;

      let option = {};  //   option代表的就是excel文件

      let dataTable = [];   //   dataTable代表excel文件中的数据内容
      if (dataList) {
        for (let i in dataList) {
          let obj = {
            考官姓名: dataList[i].name,
            身份证号码: dataList[i].idcard,
            原因: dataList[i].message
          };

          dataTable.push(obj);   //   设置excel每列获取的数据源
        }
      }

      option.filename = "不在本考点的人员清单";  //excel文件名
      //excel文件数据
      option.datas = [
        {
          //   excel文件的数据源
          sheetData: dataTable,
          //   excel文件sheet的表名
          sheetName: "模板",
          //   excel文件表头名
          sheetHeader: ["考官姓名", "身份证号码","原因"],
          //   excel文件列名
          sheetFilter: ["考官姓名", "身份证号码","原因"],
        },
      ];
      //   创建ExportJsonExcel实例对象
      let toExcel = new ExportJsonExcel(option);
      //   调用保存方法
      toExcel.saveExcel();
    },
    // 提交上传文件
    submitFileForm() {

      if(this.queryParams.sceneId==undefined||this.queryParams.exampointId==undefined)
      {
        this.$alert('导入数据请选择场次', "提示", { dangerouslyUseHTMLString: true });
        return;
      }
      this.$refs.upload.submit();
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateExaminerSceneStatus(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const rowcount = ids.length;
      this.$confirm('真的要删除'+rowcount+'条数据吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delExaminerscene(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      let that = this
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有人员签到数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          that.exploading = true;
          return exportExaminerscene(queryParams);
        }).then(response => {
          that.exploading = false;
          this.download(response.msg);
        }).catch(function() {
          that.exploading = false;
        });
    },
    countExaminerPrice(){
      if(this.queryParams.sceneId==undefined||this.queryParams.exampointId==undefined)
      {
        this.$alert('计算发放费用请选择场次', "提示", { dangerouslyUseHTMLString: true });
        return;
      }
      countExaminerPrice(this.queryParams).then(response => {
        this.getList();
      });
    }

  }
};
</script>
